(*DONT_TOUCH = "TRUE"*)
module ad_3pa1030 #(
  parameter mux_num = 10,
  parameter work_clk = 300_000_000,
  parameter ad_freq = 15_000,
  parameter start_trigger_pos = 2,
  parameter start_ref_lock_trigger_pos = 1
)
(
  input clk,
  input rst_n,
  input [9:0] ad_3pa1030_ch,
  output reg datin_bram_w_en,
  output reg [clogb2(mux_num) - 1:0] datin_bram_w_addr, 
  output reg [9:0] datin_bram_w_data,
  output reg datin_bram_w_we,
  output reg start,
  output reg start_ref_lock
);

function integer clogb2(input integer depth);
  integer tmp;
  begin
    tmp = depth;
    for (clogb2 = 0; tmp > 0; clogb2 = clogb2 + 1) 
      tmp = tmp >> 1;                          
  end
endfunction

localparam PERIOD_TICKS = work_clk / ad_freq;  // 300MHz / 15kHz = 20000

reg [clogb2(PERIOD_TICKS)-1:0] tick_cnt;
reg [clogb2(mux_num) - 1:0] addr_cnt;

always @(posedge clk or negedge rst_n) begin
  if (!rst_n) begin
    tick_cnt <= 0;
    addr_cnt <= 0;
    datin_bram_w_en <= 0;
    datin_bram_w_we <= 0;
    datin_bram_w_addr <= 0;
    datin_bram_w_data <= 0;
    start <= 0;
    start_ref_lock <=0;
  end else begin
    // Tick计数
    if (tick_cnt >= PERIOD_TICKS - 1)
      tick_cnt <= 0;
    else
      tick_cnt <= tick_cnt + 1;

    // 写数据与地址更新（仅在前 mux_num 拍）
    if (tick_cnt < mux_num) begin
      datin_bram_w_en <= 1;
      datin_bram_w_we <= 1;
      datin_bram_w_data <= ad_3pa1030_ch;
      datin_bram_w_addr <= addr_cnt;

      // start 仅在写第 start_trigger_pos 个时拉高
      start <= (addr_cnt == start_trigger_pos - 1);
      start_ref_lock <= (addr_cnt == start_ref_lock_trigger_pos - 1);

      // 地址更新
      addr_cnt <= addr_cnt + 1;
    end else begin
      datin_bram_w_en <= 0;
      datin_bram_w_we <= 0;
      start <= 0;
      start_ref_lock <= 0;
      addr_cnt <= 0;  // 每个周期结束后重置地址计数
    end
  end
end

endmodule
